package com.zzyl.common.ai;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QianfanApiClient {
    private final RestTemplate restTemplate;
    @Autowired
    private BaiduProperties baiduProperties;
    public QianfanApiClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String sendChatRequest(String prompt) {
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + baiduProperties.getToken());

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-4.0-turbo-8k");

        // 构建messages列表
        List<Map<String, String>> messages = new ArrayList<>();

        // 添加user消息
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        requestBody.put("messages", messages);

        // 创建HttpEntity对象
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(
                baiduProperties.getUrl(),
                requestEntity,
                String.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            String json = response.getBody();
            JSONObject jsonObject = JSONUtil.parseObj(json);
            JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
            String str = choices.getJSONObject("message").getStr("content");
            return str;
        } else {
            throw new RuntimeException("API请求失败: " + response.getStatusCode());
        }
    }
}
